package com.bytemonster.test;

import java.io.*;
import java.net.*;

public class TCPClient {
    public static void main(String[] args) {
        final String SERVER_IP = "127.0.0.1"; // 指定的服务器IP
        final int PORT = 8081;               // 指定的端口号

        try (Socket socket = new Socket(SERVER_IP, PORT);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(
                     new InputStreamReader(socket.getInputStream()));
             BufferedReader stdIn = new BufferedReader(
                     new InputStreamReader(System.in))) {

            System.out.println("已成功连接到服务器 " + SERVER_IP + ":" + PORT);
            System.out.print("请输入要发送的消息(输入'exit'退出): ");

            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                // 发送消息到服务器
                out.println(userInput);

                // 如果用户输入"exit"，则退出循环
                if ("exit".equalsIgnoreCase(userInput)) {
                    break;
                }

                // 读取服务器响应
                String response = in.readLine();
                if (response != null) {
                    System.out.println("服务器响应: " + response);
                } else {
                    System.out.println("服务器未返回响应，连接可能已关闭");
                    break;
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("无法找到主机: " + SERVER_IP);
            System.err.println("请检查IP地址是否正确");
        } catch (ConnectException e) {
            System.err.println("连接被拒绝: " + SERVER_IP + ":" + PORT);
            System.err.println("可能原因: 服务器未运行/防火墙阻止/网络问题");
        } catch (SocketTimeoutException e) {
            System.err.println("连接超时，服务器未响应");
        } catch (IOException e) {
            System.err.println("客户端I/O异常: " + e.getMessage());
        }

        System.out.println("客户端已断开连接");
    }
}